import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

class WidgetUtils {

  static void addSafeUse(VoidCallback callback) {
    var schedulerPhase = SchedulerBinding.instance.schedulerPhase;
    if (schedulerPhase == SchedulerPhase.persistentCallbacks) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) => callback());
    } else {
      callback();
    }
  }

  static Future<void> awaitSafeUse({VoidCallback? onPostFrame}) async {
    final completer = Completer();
    var schedulerPhase = SchedulerBinding.instance.schedulerPhase;
    if (schedulerPhase == SchedulerPhase.persistentCallbacks) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        onPostFrame?.call();
        if (!completer.isCompleted) completer.complete();
      });
    } else {
      onPostFrame?.call();
      if (!completer.isCompleted) completer.complete();
    }

    await completer.future;
  }

  static Future<void> awaitPostFrame({VoidCallback? onPostFrame}) async {
    final completer = Completer();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      onPostFrame?.call();
      if (!completer.isCompleted) completer.complete();
    });
    await completer.future;
  }
}

OverlayState overlayOf(BuildContext context) => Overlay.of(context);
